package com.lsm.sm.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.xwork.StringUtils;

public class CookieUtil {
	
	//得到指定的cookie
	public static Cookie getCookie( String key ){
		HttpServletRequest request = WebUtil.getHttpRequest();
		if( StringUtils.isBlank( key ) ){
			return null;
		}
		
		Cookie[] cookies = request.getCookies();
		if( cookies==null || cookies.length<1 ){
			return null;
		}
		
		for( Cookie cookie : cookies ){
			if( key.equals(cookie.getName()) ){
				return cookie;
			}
		}
		return null;
	}
	
	//新建 cookie 并保存
	public static void addCookie( String key, String value ){
		Cookie cookie = new Cookie( key, value );
		
		cookie.setMaxAge( 60*60*24*14 );	//保存二周
		
		WebUtil.getHttpResponse().addCookie( cookie );	//保存至响应中
	}
	
	//删除指定的 cookie
	public static void delCookie( String name ){
		Cookie cookie = getCookie( name );
		cookie.setMaxAge( 0 );
	}
	
	//为测试使用！难道这个方法，会把非本站相关的 cookie 也全部读取过来？
	public static void retrieveCookies(){
		HttpServletRequest request = WebUtil.getHttpRequest();
		Cookie[] cookies = request.getCookies();
		
		for( Cookie cookie : cookies ){
			System.out.println(
					"[ domain:" + cookie.getDomain() + ", path:" + cookie.getPath() +
					", name:" + cookie.getName() + ", value:" + cookie.getValue() +
					", expire:" + cookie.getMaxAge() + ", version:" + cookie.getVersion() +
					", secure:" + cookie.getSecure() + " ]" );
		}
	}
}
